# coding: utf-8
import datetime
import json
import os.path
import random

from flask import render_template, request, current_app, flash, \
    redirect, url_for, jsonify, make_response, Response, send_from_directory
from flask_login import login_required,current_user
from . import blog
from .. import db
from models.models import Post, Comment, User, Follow
from models.user import TestUser
from .forms import blog_form, comment_form, avatar_form


@blog.route('/')
def home():
    return jsonify(dict(status=200,msg='success'))


@blog.route('/show_post/<int:post_id>', methods=['GET', 'POST'])
def show_post(post_id):
    post = Post.query.get(post_id)
    author = User.query.get(post.author_id)
    comments = Comment.query.filter_by(post_id=post_id) \
        .order_by(Comment.timestamp.desc()).all()
    a = current_user
    if not current_user.is_authenticated:
        follow_type = '+关注'
    else:
        follow = Follow.query.filter_by(follow_id=current_user.id, followed_id=author.id).first()
        if follow is not None:
            follow_type='已关注'
        else:
            follow_type='+关注'
    users = []
    for i in comments:
        users.append(User.query.get(i.author_id))
    form = comment_form()
    return render_template('detail.html',
                           post=post, result=zip(comments, users),
                           title='文章详情', form=form, author=author, follow_type=follow_type)


@blog.route('/myblog/<user_id>', defaults={'page': 1})
@blog.route('/myblog/<user_id>/<int:page>')
@login_required
def my_blog(user_id, page):
    per_page = current_app.config['BLOG_POST_PER_PAGE']
    pagination = Post.query.filter_by(author_id=user_id) \
        .order_by(Post.timestamp.desc()).paginate(page, per_page=per_page)
    posts = pagination.items
    return render_template('index.html', pagination=pagination, posts=posts,
                           title='我的博客')


@blog.route('/about/<int:user_id>',
            defaults={'page':1,'page_fans':1,'page_follow':1},
            methods=['GET', 'POST'])
@blog.route('/about/<int:user_id>/<int:page>/<int:page_fans>/<int:page_follow>')
@login_required
def about(user_id,page,page_fans,page_follow):
    user = User.query.get(user_id)
    pagination = Post.query.filter_by(author_id=user_id) \
        .order_by(Post.timestamp.desc()).paginate(page, per_page=8)
    posts = pagination.items

    pagination_fans = Follow.query.filter_by(followed_id=user_id)\
        .paginate(page_fans, per_page=5)
    user1 = pagination_fans.items
    fans = [User.query.get(user.follow_id) for user in user1]


    pagination_follows = Follow.query.filter_by(follow_id=user_id)\
        .paginate(page_follow, per_page=5)
    user2 = pagination_follows.items
    followed = [User.query.get(user.followed_id) for user in user2]

    form = avatar_form()
    if user.about is None:
        user.about = '暂无介绍'
        if user.name is None:
            user.name = '暂无信息'
    if form.validate_on_submit():
        f = form.photo.data
        new_filename = change_filename(user.username, f.filename)
        user.avatar_s = new_filename
        db.session.commit()
        f.save(os.path.join(current_app.config['UPLOAD_PATH'], new_filename))
        return redirect(url_for('blog.about',user_id=user.id))
    if user_id!=current_user.id:
        return render_template('about.html', user=user, title='关于我', form=form,
                               posts=posts, followed=followed,pagination=pagination,
                               pagination_follows=pagination_follows,my_his='他')
    else:
        return render_template('about.html', user=user, title='关于我',form=form,
                               posts=posts, fans=fans, followed=followed,pagination=pagination,
                               pagination_follows=pagination_follows,pagination_fans=pagination_fans,
                               my_his='我')


def change_filename(username, filename):
    i = random.randint(1, 10)
    filename_list = filename.split('.')
    return username+str(i)+'.'+filename_list[-1]


@blog.route('/write', methods=['GET', 'POST'])
@login_required
def write_blog():
    form = blog_form()
    user_id = current_user.id
    if form.validate_on_submit():
        timestamp = datetime.datetime.utcnow()
        post = Post(title=form.title.data, body=form.body.data,
                    author_id=user_id, timestamp=timestamp)
        db.session.add(post)
        db.session.commit()
        flash('submit post success')
        return redirect(url_for('blog.write_blog'))
    return render_template('write.html', form=form)


@blog.route('/comment/<int:post_id>', methods=['POST'])
@login_required
def write_comment(post_id):
    form = comment_form()
    user_id = current_user.id
    if form.validate_on_submit():
        comment = Comment(author_id=user_id, post_id=post_id,
                          body=form.body.data)
        db.session.add(comment)
        db.session.commit()
        flash('submit comment success')
        return redirect(url_for('blog.show_post', post_id=post_id))
    else:
        flash('warning message')
    return redirect(url_for('blog.show_post', post_id=post_id))


@blog.route('/avatars/<path:filename>')
@login_required
def get_avatar(filename):
    file = os.path.join(current_app.config['AVATARS_SAVE_PATH'], filename)
    return file


@blog.route('/search',defaults={'page':1},methods=['post'])
@blog.route('/search/<int:page>')
def search(page):
    q = request.form.get('q')
    per_page = current_app.config['BLOG_POST_PER_PAGE']
    pagination = Post.query.whooshee_search(q).paginate(page, per_page=per_page)
    result = pagination.items
    return render_template('search.html',pagination=pagination,
                           q=q,result=result)

@blog.route('/follow',methods=['POST'])
@login_required
def follow():
    follow_id = int(request.form.get('follow_id'))
    followed_id = int(request.form.get('followed_id'))
    Type = request.form.get('type')
    if Type=='+':
        follow = Follow(follow_id=follow_id,followed_id=followed_id)
        db.session.add(follow)
        db.session.commit()
        return jsonify({'data':'success'})
    else:
        follow = Follow.query.filter_by(follow_id=int(follow_id), followed_id=int(followed_id)).first()
        db.session.delete(follow)
        db.session.commit()
        return jsonify({'data':'success'})

@blog.route('/test')
def test():
    objs = TestUser.query.all()
    data = [{"id":obj.id,"name":obj.name} for obj in objs]
    return jsonify(data=data)


@blog.route('/test/add')
def test_add():
    name = request.args.get("name",'')
    if name:
        obj = TestUser(name=name)
        db.session.add(obj)
        db.session.commit()
    return jsonify(msg='success')